<template>
  <c-form
    style="height: 80vh; overflow: auto"
    ref="formRef"
    label-width="140px"
    width="100%"
    isDialog
    :loading="loading"
    :model="formData"
    :rows="formRows"
    @submit="onSubmit"
    @reset="onReset"
  >
    <template #productDescSlot>
      <div style="width: 100%; height: 350px; padding-bottom: 50px">
        <QuillEditor
          ref="quillRef"
          v-model:content="formData.product_desc"
          :options="editorOptions"
          contentType="html"
        />
      </div>
    </template>
  </c-form>
</template>

<script setup name="manage-center.mini-config">
import { ref, computed, onMounted } from 'vue';
import { useForm } from '@/hooks/useForm';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { createProduct, editeProduct } from '@/apis/product.js';
import { ElMessage } from 'element-plus';
import { uploadFile } from '@/apis/user';

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

const emit = defineEmits(['refresh']);

const formRef = ref(null);

const quillRef = ref();

const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      ['image', 'link'], // 自定义图片上传、文件上传
      [{ header: 1 }, { header: 2 }],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }],
    ],
  },
};

const { loading, formData, submitForm } = useForm({
  initParams: {
    product_name: '',
    product_imgs: [],
    product_price: 0,
    share_title: '',
    score_count: 0,
    exchange_count: 0,
    inventory_count: 0,
    is_new: 0,
    status: 0,
    product_desc: '',
  },
});

const formRows = ref([
  { formType: 'input', prop: 'product_name', label: '商品名称：' },
  { formType: 'upload-imgs', prop: 'product_imgs', size: 2, label: '商品图片：', required: false },
  { formType: 'input', prop: 'share_title', label: '商品分享标题：', required: false },
  {
    layout: 'flex',
    children: [
      {
        formType: 'input-number',
        prop: 'product_price',
        label: '商品价格：',
        onChange: (e) => {
          console.log(e, 'ee');
          const score = e * 1000 * 1.15;
          formData.value.score_count = Math.ceil(score / 10) * 10;
          formData.value.product_score_count = `${e} x 1000 x 1.15 = ${score.toFixed(2)}`;
        },
      },
      { formType: 'input-number', prop: 'score_count', label: '兑换积分：', precision: 0 },
      { formType: 'text', prop: 'product_score_count', label: '价格计算积分：', required: false },
    ],
  },
  {
    layout: 'flex',
    children: [
      { formType: 'input-number', prop: 'exchange_count', label: '已兑换数量：' },
      { formType: 'input-number', prop: 'inventory_count', label: '库存数量：' },
    ],
  },
  {
    layout: 'flex',
    children: [
      {
        formType: 'switch',
        prop: 'is_new',
        activeValue: 1,
        inactiveValue: 0,
        label: '是否新人专享：',
      },
      { formType: 'switch', prop: 'status', activeValue: 0, inactiveValue: 1, label: '商品状态：' },
    ],
  },
  {
    formType: 'slot',
    slot: 'productDescSlot',
    prop: 'product_desc',
    label: '商品描述：',
  },
  { formType: 'input', prop: 'remark', label: '备注：', required: false },
]);

const onSubmit = async (values, instance) => {
  console.log(formData.value, 'formData');

  instance.loading = true;

  let productImgs = [];
  for (const item of formData.value.product_imgs) {
    if (!item.uploadUrl) {
      const uploadRes = await uploadFile({
        imageBase64: item.url,
        fileName: item.file.name,
      });
      if (uploadRes.code == 0) {
        productImgs.push(uploadRes.data.fileID);
        item.uploadUrl = uploadRes.data.fileID;
      }
    } else {
      productImgs.push(item.uploadUrl);
    }
  }

  if (formData.value._id) {
    const res = await editeProduct({
      ...formData.value,
      product_imgs: productImgs,
    });

    if (res.code == 0) {
      ElMessage.success('修改成功');
      modalStore.closeModal();
      emit('refresh');
    }
  } else {
    const res = await createProduct({
      ...formData.value,
      product_imgs: productImgs,
    });

    if (res.code == 0) {
      ElMessage.success('添加成功');
      modalStore.closeModal();
      emit('refresh');
    }
  }

  instance.loading = false;
};

const onReset = () => {};

const initData = () => {
  const data = modalStore.getModal('add-mall-popup');

  console.log(data, 'data');

  if (data._id) {
    const product_imgs = data.product_imgs.map((v) => {
      return { imageUrl: v, uploadUrl: v, status: 0, loading: false };
    });
    formData.value = { ...data, product_imgs: JSON.parse(JSON.stringify(product_imgs)) };
  }
};

onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped></style>
